package tableprocessor;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class MicrosoftOfficeFilesProcessor implements FileInterface
{
    private enum Type{DOC,DOCX,XLS,XLSX};
    private StringBuffer buf = new StringBuffer();
    public boolean isIam(String path)
    {
        if (getFormat(path)!=null)
        {
            return true;
        }
        return false;
    }
    public Iterator<Table> parse(String path)
    {
        return formatParse(path,getFormat(path));
    }
    public Table getTable(String path)
    {
        return null;
    }
    private Type getFormat(String path)
    {
            try
            {
                XWPFDocument xdoc = new XWPFDocument(new FileInputStream(path));
                return Type.DOCX;
            }
            catch (Exception e){/*e.printStackTrace();*/}
            try
            {
                HWPFDocument doc = new HWPFDocument(new FileInputStream(path));
                return Type.DOC;
            }catch(Exception e){/*e.printStackTrace();*/}
            try
            {
                XSSFWorkbook xdoc = new XSSFWorkbook(new FileInputStream(path));
                return Type.XLSX;
            }
            catch (Exception e){/*e.printStackTrace();*/}
            try
            {
                HSSFWorkbook doc = new HSSFWorkbook(new FileInputStream(path));
                return Type.XLS;
            }catch(Exception e){/*e.printStackTrace();*/}
       return null;
    }
    private Iterator<Table> formatParse(String path,Type t)
    {
        switch(t)
        {
            case DOC:
            {
                return parseDoc(path);
            }
            case DOCX:
            {
                return parseDocX(path);
            }
            case XLS:
            {
                return parseXLS(path);
            }
        }
        return null;
    }
    private Iterator<Table> parseXLS(String path)
    {
        List<Table> tlist = new ArrayList<Table>();
        Table t = new Table();
        tlist.add(t);
        File inputWorkbook = new File(path);
        Workbook w;
        try
        {
            w = Workbook.getWorkbook(inputWorkbook);
            int shitNum = w.getNumberOfSheets();
            for (int i = 0 ; i < shitNum; i++)
            {
                Sheet sheet = w.getSheet(i);
                for (int j = 0 ; j < sheet.getRows(); j++)
                {
                   Cell [] cellMas = sheet.getRow(j);
                   t.insertRow(j);
                   for (int k = 0 ; k < cellMas.length; k++)
                   {
                       if (!cellMas[k].getContents().isEmpty())
                       {
                           t.addToRow(j, cellMas[k].getContents());
                       }
                   }
                }
            }
        }
        catch (IOException ex)
        {
           ex.printStackTrace();
        }
        catch (BiffException ex)
        {
            ex.printStackTrace();
        }
        return tlist.iterator();
    }
    private Iterator<Table> parseDoc(String path)
    {
        //parse1(path);
        return parse1(path);
    }
     private Iterator<Table> parseDocX(String path)
     {
          List<Table> tlist = new ArrayList<Table>();

          return tlist.iterator();
     }
    public void saveToDoc(String path)throws IOException
    {
        POIFSFileSystem fs = new POIFSFileSystem();
        DirectoryEntry directory = fs.getRoot();
        directory.createDocument("WordDocument", new ByteArrayInputStream(
        buf.toString().getBytes()));
        File f = new File(path);
        FileOutputStream out = new FileOutputStream(f);
        fs.writeFilesystem(out);
        out.close();
    }
    public void addCategory(String content) 
    {
        buf.append(content);
    }
    //test methods
    private Iterator<Table> parse1(String path)
    {
       FileInputStream finStream = null;
       List<Table> tlist = new ArrayList<Table>();
       Table t = new Table();
        try {

              tlist.add(t);
            File docFile = new File(path);
            finStream = new FileInputStream(docFile.getAbsolutePath());
            HWPFDocument doc = new HWPFDocument(finStream);
            WordExtractor wordExtract = new WordExtractor(doc);
            String[] dataArray = wordExtract.getParagraphText();
            for (int i = 0; i < dataArray.length; i++)
            {
                if (!dataArray[i].isEmpty())
                {
                    t.insertRow(i);
                    //for (int j = 0 ; j < dataArray.length; j++)
                    //{
                        t.insertData(i, 0, dataArray[i].substring(0, dataArray[i].length()-1));
                       // System.out.println(dataArray[i].substring(0, dataArray[i].length()-1));
                    //}
                    
                }
                //System.out.println(dataArray[i]);
            }
          
            return tlist.iterator();
        }
        catch (IOException ex)
        {
           ex.printStackTrace();
            return null;
        }

        finally
        {
            try {
                finStream.close();
                return tlist.iterator();
            } catch (IOException ex) {
                ex.printStackTrace();
                 return null;
            }
        }
    }
    private Iterator<Table> parse2(String path)
    {
        FileInputStream finStream = null;
        List<Table> tlist = new ArrayList<Table>();
        Table t = new Table();
        tlist.add(t);
        try
        {
           HWPFDocument doc = new HWPFDocument(new FileInputStream(path));
           Range range = doc.getRange();
           TableIterator iter = new TableIterator(range);
           org.apache.poi.hwpf.usermodel.Table table = null;
           while(iter.hasNext())
           {
              table = iter.next();
              for (int i = 0; i < table.numRows(); i++)
              {
                  t.insertRow(i);
                 for (int j = 0; j < table.getRow(i).numCells(); j++)
                 {
                       TableCell tc = table.getRow(i).getCell(j);
                       t.setData(i, j, tc.text());
                 }
               }
            }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        return tlist.iterator();
    }
}

